(function($) {
	$.initIFrame = {
			/**iframe路径跳转*/
			iframeQuery : function(type){
				$("#iframe").attr("src","ifarmeConfig/toIFrameManager?type="+type);
			}
			/**格式化HTML代码*/
			,formatContent:function(flag){
				var content = $("#iframe").contents()[0];
				var head = $(content).find("head");
				var body = $(content).find("body");
				head.find("link").each(function(index, obj){
					$(this).attr("href",obj.href);
				});
				head.find("script[src]").each(function(index, obj){
					var scriptSrc = obj.src;
					if(flag && scriptSrc.indexOf("jquery-")!=-1){
						$(this).remove();
					}else{
						$(this).attr("src",obj.src);
					}
				});
				body.find("link").each(function(index, obj){
					$(this).attr("href",obj.href);
				});
				body.find("script[src]").each(function(index, obj){
					var scriptSrc = obj.src;
					if(flag && scriptSrc.indexOf("jquery-")!=-1){
						$(this).remove();
					}
				});
				body.find(".glyphicon").each(function(){
					$(this).remove();
				});
				body.find(".zbtp").each(function(index, obj){
					var tagName = $(this)[0].tagName;
					if ("IMG" == tagName) {
						$(this).attr("src",obj.src);
					} else {
						var back = $(this).css('backgroundImage');
						back = back.substring(5,back.length-2);
						$(this).removeAttr("style");
						$(this).css("background-image","url(" + back + ")");
					}
				});
				
				/**区域卫生还原*/
				body.find("#tab-ul").children().eq(0).click();
				/**工作报告还原*/
				body.find(".swiper-pagination-bullet").eq(0).click();
				if(body.find(".report-container").find(".icon-arrow-up").eq(0).hasClass("active")){
					$(this).click();
				};
				if(body.find(".report-container").find(".icon-arrow-up").eq(1).hasClass("active")){
					$(this).click();
				}
				
				var html = "<html>" + head.prop("outerHTML") + body.prop("outerHTML") + "</html>";
				html = $.ReplaceIpdk.replaceIpdk(html,"#ipdk#");
				html = $.ReplaceIpdk.replaceBgImg(html,"&quot;");
				return html;
			}
		/**初始化拖动图片及指标信息等事件*/
		,initFrame : function(id,flag){
			$("#iframe").data("id", id);
			/**添加图片拖放事件*/
			$("#iframe").contents().find(".zbtp-container").each(function() {
				initAllow($(this));
				initDropImg($(this));
			});
			/**添加指标拖放事件*/
			$("#iframe").contents().find(".zbxx").each(function() {
				initAllow($(this));
				initDropZbxx($(this));
			});
			/**添加点击显隐指标单位*/
			$("#iframe").contents().find(".zbdw").each(function() {
				if(flag){
					initClickZbdw($(this),true);
				}else{
					initClickZbdw($(this));
				}
			});
			/**添加点击指标修改名称*/
			$("#iframe").contents().find(".zbmc").each(function() {
				initClickZbmc($(this));
			});
			/**添加点击显示下拉框*/
			$("#iframe").contents().find("#sjwd").each(function() {
				initClickSjwd($(this));
			});
		}
		/**删除页面引用文件*/
		,removeLink : function(){
			$("#iframe").contents().find("head").find(".iframe-script").each(function(){
				$(this).remove();
			});
		}
		/**初始化修改指标名称，指标SQL的文本框*/
		, initView : function(){
			$("#bcZbmc").on("click",function(){
				var zbmc = $(".form-control").val();
				$("#iframe").contents().find(".curr-selected-zbmc:eq(0)").text(zbmc);
				$(".form-control").val("");
				$("#exampleModal").modal("hide");
			});
			$("#exampleModal").on("hide.bs.modal", function(){
				$("#iframe").contents().find(".curr-selected-zbmc").removeClass("curr-selected-zbmc");
			});
			$("#sqlModal").on("hide.bs.modal", function(){
				$("#iframe").contents().find(".curr-selected-sql").removeClass("curr-selected-sql");
				$("#modal-sql").empty();
			});
			/**保存时间维度*/
			$("#bcSjwd").on("click",function(){
				var options=$("#sjwdSelect option:selected");
				if(options.val()!=0){
					$("#iframe").contents().find("#sjwd").attr("sjwd",options.val());
					$("#disabled").modal("hide");
				}
			});
		}
		/**查询配置项目指标*/
		,queryPzxm : function(type){
			if(type=="sy"){
				$.QuickRemote.AjaxJson("ifarmeConfig/queryPzxm", queryPzxmHandler);
			}else{
				$.QuickRemote.AjaxJson("ifarmeConfig/queryZdyzbxm", queryPzxmHandler, {type:type});
			}
		}
		/**保存页面信息*/
		,btnSaveHandler : function(type){
			var content = this.formatContent();
			var viewContent = this.formatContent(true);
			var id = $("#iframe").data("id");
			/**undefine转""*/
			if(StringUtils.isEmpty(id)) id="";
			var params = {viewContent: encodeURIComponent(viewContent), content: encodeURIComponent(content), type: type, id: id};
			$.QuickRemote.AjaxJson("ifarmeConfig/saveConfig", saveConfigHandler, params);
		}
		/** 查询页面的启用状态 */
		,queryState : function(type){
			$.QuickRemote.AjaxJson("ifarmeConfig/queryState", function(result)
			{
				initStateBtn(result.STATE);
			}, {
				TYPE : type
			});
		}
		,btnUpdateState : function(type){
			var btn = $("#stateBtn");
			var state = btn.attr("state") || "0";//默认是禁用
			state = state == "0" ? "1" : "0";//点击按钮，改变状态
			if (state == "0" || validate())
			{
				$.QuickRemote.AjaxJson("ifarmeConfig/updateState", updateStateHandler,
				{
					TYPE : type,
					STATE : state
				}, {
					STATE : state
				});
			}
		}
		,validate : function(type){
			var flag = true;
			//校验指标是否配置
			$("#iframe").contents().find(".zbz").each(function(i, item)
			{
				var resid = $(item).attr("resid");
				if (!resid)
				{
					$.QuickAlert.alertConfirm({content:"校验不通过，有指标未配置，是否继续保存？", callback: function(){
						$.initIFrame.btnSaveHandler(type);
					}});
					flag = false;
					return false;
				}
			});
			//校验图表的sql是否配置
			if (flag)
			{
				$("#iframe").contents().find("[_echarts_instance_]").each(function(i, item)
				{
					var sql = $(item).attr("sql");
					if (!sql)
					{
						$.QuickAlert.alertConfirm({content:"校验不通过，有图表的SQL未配置，是否继续保存？", callback: function(){
							$.initIFrame.btnSaveHandler(type);
						}});
						flag = false;
						return false;
					}
				});
			}
			return flag;
		}
	}
	
	/**配置项目指标回调*/
	function queryPzxmHandler(result)
	{
		var images = result["images"];
		createImages(images);
		var dzb = result["dzb"];
		createZb(dzb);
	}
	
	/**保存按钮回调*/
	function saveConfigHandler(result)
	{
		var state = result["state"];
		if(state == "true")
		{
			var id = result["id"];
			$("#iframe").data("id", id);
			$.QuickAlert.alertNormal("保存成功",{
				callback : function(){
					location.reload();
				}
			});
		}
		else
		{
			$.QuickAlert.alertFail({
				content: result["faultInfo"]
			});
		}
	}
	
	function initAllow(jq) {
		$(jq).on("dragover", function(evt) {
			evt.preventDefault();
		});
	}

	/**放下图片*/
	function initDropImg(jq) {
		$(jq).on("drop",function(evt) {
			var dataTransfer = evt.originalEvent.dataTransfer;
			var type = dataTransfer.getData("type");
			if (type != "img") {
				return false;
			} else {
				var config = JSON.parse(dataTransfer.getData("config"));
				/**找到zbtp的标签*/
				var id = config["id"];
				var url = "/image/recriveImage/" + id;
				var target = $(this).find(".zbtp:eq(0)");
				var tagName = $(target)[0].tagName;
				url = "http://"+$.QuickUrlUtils.getHostProject()+url;
				if ("IMG" == tagName) {
					$(target).attr("src", url);
				} else {
					$(target).removeAttr("style");
					$(target).css('background-image','url(' + url + ')');
				}
			}
		});
	}

	/**放下指标*/
	function initDropZbxx(jq) {
		$(jq).on("drop", function(evt) {
			var dataTransfer = evt.originalEvent.dataTransfer;
			var type = dataTransfer.getData("type");
			if (type != "zb") {
				return false;
			} else {
				var config = JSON.parse(dataTransfer.getData("config"));
				var zbmc = $(this).find(".zbmc:eq(0)");
				$(zbmc).text(config["ZBMC"]);
				var zbz = $(this).find(".zbz:eq(0)");
				$(zbz).text("90");
				$(zbz).attr("resid",config["RESID"]);
				var zbdw = $(this).find(".zbdw:eq(0)");
				$(zbdw).text(config["DW"]);
				$(zbdw).attr("ref",config["RESID"]);
				$(this).attr("id", config["RESID"]);
			}
		});
	}

	/**点击指标修改名称*/
	function initClickZbmc(jq) {
		$(jq).on("click", function() {
			$("#exampleModal").modal("show");
			$(this).addClass("curr-selected-zbmc");
			$(".zbmc-control").val($(this).text());
		});
	}
	
	/**点击显示下拉框*/
	function initClickSjwd(jq) {
		$(jq).on("click", function() {
			$("#disabled").modal("show");
		});
	}

	/**初始点击显隐指标单位*/
	function initClickZbdw(jq,flag) {
		var style = "";
		if(flag){
			style = "position: absolute; margin-top: 10px;";//绝对定位
		}
		var url = "http://"+$.QuickUrlUtils.getHostProject()+"/styles/images/";
		$(jq).each(function(){
			if(!$(this).next().length){
				var show = $("<img style=' "+style+" z-index: 999;' class='glyphicon glyphicon-eye-close' src='"+url+"close.png"+"'></img>");
				$(show).on("click",function(){
					var childrenClass = $(this).attr("class");
					if(childrenClass=="glyphicon glyphicon-eye-open"){
						$(this).prev().show();
						$(this).attr("src",url+"close.png");
						$(this).removeClass("glyphicon glyphicon-eye-open").addClass("glyphicon glyphicon-eye-close");
					}else{
						$(this).prev().hide();
						$(this).attr("src",url+"open.png");
						$(this).removeClass("glyphicon glyphicon-eye-close").addClass("glyphicon glyphicon-eye-open");
					}
				});
				$(this).after(show);
			}
		});
	}

	/**创建图标*/
	function createImages(images)
	{
		var ary = JSON.parse(images);
		$.each(ary, function(index, item){
			var id = this["_id"]["$oid"];
			var TPMS = this["TPMS"];
			var src = $.QuickUrlUtils.getProjectName() + "/image/recriveImage/" + id;
			var imgBlock = $($("#item-img").html());
			this["id"] = id;
			$(imgBlock).data("config", this);
			$(imgBlock).find("img").attr("lay-src", src);
			$(imgBlock).find("span.TPMS").text(TPMS);
			$(imgBlock).attr("draggable", true);
			$(imgBlock).on("dragstart", dragImg);
			$(imgBlock).appendTo($("#imgContainer"));
		});
		layui.use('flow', function() {
			var flow = layui.flow;
			flow.lazyimg({
				scrollElem : ".imgContainer"
			});
		});
	}

	/**创建指标*/
	function createZb(dzb)
	{
		var ary = JSON.parse(dzb);
		$.each(ary, function(){
			var zb = $($("#item-zb").html());
			var id = this["RESID"];
			var mc = this["ZBMC"];
			var dw = this["DW"];
			$(zb).data("config", this);
			$(zb).text(mc + "(" + dw + ")");
			$(zb).attr("id", id);
			$(zb).attr("draggable", true);
			$(zb).on("dragstart", dragZb);
			$(zb).appendTo($("#zbContainer"));
		});
	}

	function dragImg(evt)
	{
		drag(evt, $(this), "img");
	}

	function dragZb(evt)
	{
		drag(evt, $(this), "zb");
	}

	function drag(evt, target, type)
	{
		var config = $(target).data("config");
		var dataTransfer = evt.originalEvent.dataTransfer;
		dataTransfer.setData("type", type);
		dataTransfer.setData("config", JSON.stringify(config));
	}
	
	/**  根据查询的状态，初始化按钮 */
	function initStateBtn(state)
	{
		var title = $(".navbar-text");
		var span =  title.next("button").find("span");
		if (state == "0")
		{
			span.addClass("glyphicon-star-empty").removeClass("glyphicon-star");
			$("#stateBtn").attr("state", state).html(" 启用");
		} else
		{
			span.addClass("glyphicon-star").removeClass("glyphicon-star-empty");
			$("#stateBtn").attr("state", state).html(" 禁用");
		}
	}
	
	/** 更新操作的结果  */
	function updateStateHandler(result, p)
	{
		var state = p.STATE;
		if (result.state == "true")
		{
			initStateBtn(state);
			$.QuickAlert.alertNormal("更新成功!");
		} else
		{
			$.QuickAlert.alertFail({
				content : "更新失败!" + result.failInfo
			});
		}
	}
	
	/** 校验是否可以启用  */
	function validate()
	{
		var flag = true;
		//校验指标是否配置
		$("#iframe").contents().find(".zbz").each(function(i, item)
		{
			var resid = $(item).attr("resid");
			if (!resid)
			{
				$.QuickAlert.alertFail({
					content : "校验不通过，有指标未配置"
				});
				flag = false;
				return false;
			}
		});
		//校验图表的sql是否配置
		if (flag)
		{
			$("#iframe").contents().find("[_echarts_instance_]").each(function(i, item)
			{
				var sql = $(item).attr("sql");
				if (!sql)
				{
					$.QuickAlert.alertFail({
						content : "校验不通过，有图表的SQL未配置"
					});
					flag = false;
					return false;
				}
			});
		}
		return flag;
	}
	
})(jQuery);